from django.http import HttpResponse
from django.contrib.csrf.middleware import csrf_exempt

import simplejson
from lyricemo.models import EmoWord,EmoPattern,EmoWordAnnoOk
from lyricsplit.models import LyricLrc

@csrf_exempt
def add_emo_word(request):
    w = request.POST['w']
    v = int(request.POST['v'])
    if EmoWord.all().filter('w =',w).count() != 0:
        return HttpResponse(simplejson.dumps({
            'code':1,
            'data':{
                'errorMessage':'no emo word already exist'
                }}))
    else:
        ew = EmoWord()
        ew.w = w
        ew.v = v
        ew.desp = "{}"
        ew.put()

        # update the emo_dict_cache
        # force_update_emodict()

        return HttpResponse(simplejson.dumps({
            'code':0
            }))


@csrf_exempt
def add_emo_pattern(request):
    try:
        p = request.POST['p']
        k = request.POST['k']

        ep = EmoPattern()
        ep.desp = p
        ep.lrc = LyricLrc.get(k)
        ep.anno_ip = request.META['REMOTE_ADDR']
        ep.put()
        return HttpResponse(simplejson.dumps({
                'code':0
            }))
    except Exception,e:
        return HttpResponse(simplejson.dumps({
                'code':1,
                'data':{
                    'errorMessage':str(e)
                    }}))


@csrf_exempt
def reset_emo_word_anno(request):
    try:
        k = request.POST['k']
        lrc = LyricLrc.get(k)
        if EmoWordAnnoOk.all().filter('lrc =',lrc).count() == 0:
            ewao = EmoWordAnnoOk()
            ewao.anno_ok = 0
            ewao.lrc = lrc
            ewao.put()
        else:
            for ewao in EmoWordAnnoOk.all().filter('lrc =',lrc):
                ewao.anno_ok = 0
                ewao.put()
        return HttpResponse(simplejson.dumps({
                'code':0
            }))
    except Exception,e:
        return HttpResponse(simplejson.dumps({
                'code':1,
                'data':{
                    'errorMessage':str(e)
                    }}))

@csrf_exempt
def download_lex(request):
    try:
        w_list = []
        for ew in EmoWord.all():
            w_list.append( (ew.w,ew.v) )
        return HttpResponse(simplejson.dumps({
            'code':0,
            'data':{
                'w_list':w_list
                }}))
    except Exception,e:
        return HttpResponse(simplejson.dumps({
                'code':1,
                'data':{
                    'errorMessage':str(e)
                    }}))
